package main

import (
	"fmt"
	"github.com/urfave/cli"
	"log"
	"net"
	"os"
)

func main() {
	app := cli.NewApp()

	cli.VersionFlag = cli.BoolFlag{
		Name:  "version, V",
		Usage: "print only the version",
	}
	app.Name = "Website Lookup CLI"
	app.Usage = "Let's you query IPs, CNAMEs and Name Servers!"
	app.Version = "0.0.1"

	app.UseShortOptionHandling = true
	app.Commands = []cli.Command{
		{
			Name:      "ns",
			Usage:     "Looks Up the NameServers for a Particular Host",
			ArgsUsage: "[host1 host2 ...]",
			Action: func(c *cli.Context) (err error) {
				for _, host := range c.Args() {
					_, err = AnaNs(host)
				}
				return
			},
		},
		{
			Name:      "cname",
			Usage:     "Looks up the CNAME for a particular host",
			ArgsUsage: "[host1 host2 ...]",
			Action: func(c *cli.Context) (err error) {
				for _, host := range c.Args() {
					_, err = AnaCname(host)
				}
				return
			},
		},
		{
			Name:      "ip",
			Usage:     "Looks up the IP addresses for a particular host",
			ArgsUsage: "[host1 host2 ...]",
			Action: func(c *cli.Context) (err error) {
				for _, host := range c.Args() {
					_, err = AnaIp(host)
				}
				return
			},
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}

func AnaNs(host string) (ns []*net.NS, err error) {
	ns, err = net.LookupNS(host)
	if err == nil {
		if ns != nil && len(ns) > 0 {
			fmt.Printf("-NameServers for host:%s:\n", host)
			for _, server := range ns {
				fmt.Println("\t--", server.Host)
			}
		} else {
			fmt.Printf("NameServers is not found, for host:%s\n", host)
		}
	}
	return
}

func AnaCname(host string) (cname string, err error) {
	cname, err = net.LookupCNAME(host)
	if err == nil {
		if len(cname) > 0 {
			fmt.Printf("-Cname for host:%s:\n", host)
			fmt.Println("\t--", cname)
		} else {
			fmt.Printf("Cname is not found, for host:%s\n", host)
		}
	}
	return
}

func AnaIp(host string) (ips []net.IP, err error) {
	ips, err = net.LookupIP(host)
	if err == nil {
		if ips != nil && len(ips) > 0 {
			fmt.Printf("-IP for host:%s:\n", host)
			for _, server := range ips {
				fmt.Println("\t--", server)
			}
		} else {
			fmt.Printf("IP is not found, for host:%s\n", host)
		}
	}
	return
}
